import requests
import ffmpeg
import os
from pydub import AudioSegment

from config.mysql_config import get_db
from config.ppt_config import PICTURE_FOLDER, AUDIO_FOLDER, PPTX_FOLDER, RESOURCES_FOLDER, VIDEO_FOLDER
from dao.slide_dao import update_slide_fields
from service.ppt_service import update_ppt_fields_service, update_ppt_state_service, get_ppt_by_id_service
from service.slide_service import update_slide_fields_service, get_slides_by_ppt_service, \
    get_one_slide_ppt_index_service
from common.pptx_common import delete_folder, get_video_duration, delete_file
from utils.log import logger

from utils.pptx_to_picture import ppt_to_picture
from utils.store_minIo import store_slide_minio, store_audio_minio, store_video_minio
from utils.data_generate import text_generate, audio_generate, create_video
import time

def ppt_analyze_ai(ppt_id: int, ppt_path):

    """
    进入文件解析生成视频方法，对PPT进行解析生成视频.此时输入是AI-PPT
    :param ppt_path: ppt所处的完整的文件绝对路径
    :param ppt_id: PPT对应ID
    :param file: 用户上传的PPT文件
    :return: 异步任务
    """

    logger.info(f"进入对AI-PPT解析生成视频方法")

    with get_db() as db:
        ppt = get_ppt_by_id_service(ppt_id)

    ppt_name = ppt["ppt_name"]

    # 首先将PPT转换成图片,得到的是该PPT包含的图片数量
    picture_count = ppt_to_picture(ppt_path, ppt_name)

    time.sleep(5)  # 睡眠3秒
    print("3秒后继续执行")

    # 将PPT图片数量存入到数据库中
    ppt_page_json = {"ppt_pages": picture_count}
    with get_db() as db:
        ppt = update_ppt_fields_service(ppt_id, ppt_page_json)

    # 传入的图片文件地址
    file_path = os.path.join(PICTURE_FOLDER, ppt_name)

    # 将保存到本地的图片存入到minio
    res = store_slide_minio(file_path, ppt_name, picture_count)
    # 获取第一个对象的第一个键
    first_key = list(res[0].keys())[0]
    # 获取该键对应的值
    first_value = res[0][first_key]
    update_fields = {"ppt_image_path": first_value}
    # 将index为1的img_url存储到PPT表中
    ppt = update_ppt_fields_service(ppt_id, update_fields)

    # 对slides中的img_url字段一个一个进行更新
    slides = []
    for item in res:  # res形如：[{'1': 'http://121.195.170.40:9000/slide-picture/电力行业PPT-1'}, {'2': 'http://121.195.170.40:9000/slide-picture/电力行业PPT-2'}, {'3': 'http://121.195.170.40:9000/slide-picture/电力行业PPT-3'}]
        for key, value in item.items():  # item 是字典
            # 拿到对应的slides
            slide = get_one_slide_ppt_index_service(ppt_id, int(key))
            slide_fields = {"slide_image_path": value}
            slide = update_slide_fields_service(slide["slide_id"], slide_fields)
            slides.append(slide)

    # 对PPT的每一个幻灯片中的演讲稿进行润色，
    for slide in slides:
        text = text_generate(slide["text"])
        slide_text = {"text": text}
        # 润色完毕之后再重新存储至mysql
        slide = update_slide_fields_service(slide["slide_id"], slide_text)

    # 从数据库中拿出对应PPT_id的所有的slides
    slides = get_slides_by_ppt_service(ppt_id)

    # 对其中所有的slide.text都使用cosyvoice服务转化成filename_index.wav文件
    for slide in slides:
        # file_info 是一个字典，包含有filename和filepath,还有音频时长
        file_info = audio_generate(slide["text"], ppt_name, slide["slide_index"])

        # 将该wav文件存储到minio服务器上
        slide_audio_path = store_audio_minio(file_info["file_path"], file_info["file_name"])
        slide_fields = {"slide_audio_path": slide_audio_path,
                               "slide_audio_duration": file_info["slide_audio_duration"]}
        #   将mini体地址信息和音频时长存储到mysql数据库
        res = update_slide_fields_service(slide["slide_id"], slide_fields)
        logger.info("更新后的音频时长为：", res["slide_audio_duration"], "minio地址为:", res["slide_audio_path"])

    # 拿到PPT的数据
    ppt = get_ppt_by_id_service(ppt_id)

    # 开始生成视频
    output_path = create_video(ppt_name, ppt["ppt_pages"])

    # 存储视频到minio云端
    video_url = store_video_minio(output_path,ppt_name)

    # 获取视频的长度
    video_duration = get_video_duration(video_url)

    # 添加数据库中的ppt的ppt_video_path和ppt_video_duration的值

    update_fields = {"ppt_video_path": video_url,
                     "ppt_video_duration": video_duration}
    # 将index为1的img_url存储到PPT表中
    ppt = update_ppt_fields_service(ppt_id, update_fields)

    # 将本地存储的图片删除掉
    picture_path = os.path.join(PICTURE_FOLDER, ppt_name)
    delete_folder(picture_path)

    # 将本地存储的音频删除掉
    audio_path = os.path.join(AUDIO_FOLDER, ppt_name)
    delete_folder(audio_path)

    # 将本地存储的视频删除掉
    video_path = os.path.join(VIDEO_FOLDER, ppt_name)
    delete_file(video_path)

    # 修改state状态==3，代表着解析完成
    update_ppt_state_service(ppt_id, 3)

def ppt_analyze_non_ai(ppt_id: int, file):
    """
    进入文件解析生成视频方法，对PPT进行解析生成视频.此时输入是用户自己的PPT
    :param ppt_id: PPT对应ID
    :param file: 用户上传的PPT文件
    :return: 异步任务
    """
    logger.info(f"进入对AI-PPT解析生成视频方法")
    return None


